package com.littlecar.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 描述：
 *
 * @author littlecar
 * @date 2020/3/2 9:31
 */
@Component
public class CookieFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;//优先级，数字越小，优先级越高
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String requestURI = request.getRequestURI();
        if ( StringUtils.equals(requestURI,"/security/login")) {
            return true;//表示需要过滤
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie :
                cookies) {
            System.out.println("CookieFilter----->" + cookie.getName());
            if (StringUtils.equals(cookie.getName(), "ZuulToken")) {//说明已经存在ZuulToken
                return null;
            }
        }
        UUID uuid = UUID.randomUUID();
        Cookie cookie = new Cookie("ZuulToken",uuid.toString());
        cookie.setMaxAge(-1);//过期时间
        cookie.setPath("/");//路径
        response.addCookie(cookie);
        return null;
    }
}
